package com.huashi.dealer.modular.controller.store.upload;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huashi.dealer.commonEntity.UploadFile;
import com.huashi.dealer.commonEntity.UploadGroup;
import com.huashi.dealer.core.page.PageFactory;
import com.huashi.dealer.core.pojo.CommonResult;
import com.huashi.dealer.modular.business.upload.param.GroupParam;
import com.huashi.dealer.modular.business.upload.service.UploadGroupService;
import com.huashi.dealer.modular.business.upload.service.UploadService;
import com.huashi.dealer.modular.business.upload.vo.ImageLibraryVo;
import com.huashi.dealer.core.util.FileUploadUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Store端图片库管理控制器
 * 对应PHP项目的/store/upload/library功能
 */
@Slf4j
@Tag(name = "Store端图片库管理控制器")
@RestController("storeLibraryController")
@RequestMapping("/store/upload/library")
@Validated
public class LibraryController {

    @Resource
    private UploadService uploadService;

    @Resource
    private UploadGroupService uploadGroupService;

    @Resource
    private FileUploadUtil fileUploadUtil;

    /**
     * 上传图片到指定分组
     * 对应PHP的/store/upload/image接口
     */
    @PostMapping("/upload")
    @Operation(summary = "上传图片到指定分组")
    public CommonResult<ImageLibraryVo.FileItemVo> uploadImage(
            @RequestParam("file") MultipartFile file,
            @RequestParam(defaultValue = "0") Long groupId,
            @RequestParam(defaultValue = "image") String type) {

        try {
            // 判定file必须是图片
            if (file == null || file.isEmpty()) {
                return CommonResult.error("上传文件不能为空");
            }

            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return CommonResult.error("只允许上传图片文件");
            }
            // 上传图片
            UploadFile uploadFile = fileUploadUtil.uploadImage(file);
            
            // 设置分组ID和文件类型
            uploadFile.setGroupId(groupId);
            uploadFile.setFileType(type);
            uploadFile.setWxappId(10001L); // 默认小程序ID
            
            // 保存到数据库
            uploadService.save(uploadFile);
            
            // 转换为返回格式
            ImageLibraryVo.FileItemVo fileItemVo = convertToFileItemVo(uploadFile);
            
            return CommonResult.data(fileItemVo);
        } catch (Exception e) {
            log.error("图片上传失败", e);
            return CommonResult.error("图片上传失败：" + e.getMessage());
        }
    }
    /**
     * 上传图片
     */
    @PostMapping("/file")
    @Operation(summary = "上传文件")
    public CommonResult<UploadFile> uploadImage(@RequestParam("iFile") MultipartFile file) {
        try {
            UploadFile responseParam = uploadService.uploadImage(file);
            return CommonResult.data(responseParam);
        } catch (Exception e) {
            return CommonResult.error("上传失败：" + e.getMessage());
        }
    }
    /**
     * 批量上传图片
     * 对应PHP的多图片上传功能
     */
    @PostMapping("/uploadBatch")
    @Operation(summary = "批量上传图片")
    public CommonResult<List<ImageLibraryVo.FileItemVo>> uploadImages(
            @RequestParam("files") MultipartFile[] files,
            @RequestParam(defaultValue = "0") Long groupId,
            @RequestParam(defaultValue = "image") String type) {
        try {
            if (files == null || files.length == 0) {
                return CommonResult.error("上传文件不能为空");
            }
            
            List<ImageLibraryVo.FileItemVo> uploadedFiles = new ArrayList<>();
            int successCount = 0;
            
            for (MultipartFile file : files) {
                try {
                    // 上传单个文件
                    UploadFile uploadFile = fileUploadUtil.uploadImage(file);
                    uploadFile.setGroupId(groupId);
                    uploadFile.setFileType(type);
                    uploadFile.setWxappId(10001L);
                    
                    // 保存到数据库
                    uploadService.save(uploadFile);
                    
                    // 转换为返回格式
                    ImageLibraryVo.FileItemVo fileItemVo = convertToFileItemVo(uploadFile);
                    uploadedFiles.add(fileItemVo);
                    successCount++;
                } catch (Exception e) {
                    log.error("单个图片上传失败: {}", file.getOriginalFilename(), e);
                }
            }
            
            if (successCount == files.length) {
                return CommonResult.data(uploadedFiles);
            } else {
                log.warn("批量上传部分失败：成功{}张，失败{}张", successCount, files.length - successCount);
                return CommonResult.data(uploadedFiles);
            }
        } catch (Exception e) {
            log.error("批量上传图片失败", e);
            return CommonResult.error("批量上传图片失败：" + e.getMessage());
        }
    }

    /**
     * 获取文件库列表
     * 对应PHP的fileList方法
     */
    @GetMapping("/fileList")
    @Operation(summary = "获取文件库列表")
    public CommonResult<ImageLibraryVo> getFileList(
            @RequestParam(defaultValue = "image") String type,
            @RequestParam(defaultValue = "-1") Integer groupId) {
        try {
            ImageLibraryVo result = new ImageLibraryVo();

            // 获取分组列表
            List<UploadGroup> groupList = uploadGroupService.getGroupList(type);
            List<ImageLibraryVo.GroupVo> groupVoList = new ArrayList<>();
            
            // 添加"全部"分组
            ImageLibraryVo.GroupVo allGroup = new ImageLibraryVo.GroupVo();
            allGroup.setGroupId(-1L);
            allGroup.setGroupName("全部");
            allGroup.setIsDefault(groupId == -1);
            groupVoList.add(allGroup);
            
            // 添加"未分组"分组
            ImageLibraryVo.GroupVo uncategorizedGroup = new ImageLibraryVo.GroupVo();
            uncategorizedGroup.setGroupId(0L);
            uncategorizedGroup.setGroupName("未分组");
            uncategorizedGroup.setIsDefault(groupId == 0);
            groupVoList.add(uncategorizedGroup);
            
            // 添加自定义分组
            for (UploadGroup group : groupList) {
                ImageLibraryVo.GroupVo groupVo = new ImageLibraryVo.GroupVo();
                groupVo.setGroupId(group.getGroupId());
                groupVo.setGroupName(group.getGroupName());
                groupVo.setSort(group.getSort());
                groupVo.setIsDefault(group.getGroupId().equals(groupId.longValue()));
                groupVoList.add(groupVo);
            }
            result.setGroupList(groupVoList);

            // 获取文件列表
            Page<UploadFile> page = PageFactory.defaultPage();
            LambdaQueryWrapper<UploadFile> queryWrapper = new LambdaQueryWrapper<>();
            
            // 根据分组ID筛选
            if (groupId != -1) {
                queryWrapper.eq(UploadFile::getGroupId, groupId);
            }
            // 根据文件类型筛选
            if (!"".equals(type)) {
                queryWrapper.eq(UploadFile::getFileType, type);
            }
            // 只查询非用户上传且未删除的文件
            queryWrapper.eq(UploadFile::getIsUser, 0)
                        .eq(UploadFile::getIsRecycle, 0);
            // 按文件ID倒序
            queryWrapper.orderByDesc(UploadFile::getFileId);

            Page<UploadFile> filePage = uploadService.page(page, queryWrapper);
            
            // 转换文件列表
            ImageLibraryVo.FileListVo fileListVo = new ImageLibraryVo.FileListVo();
            List<ImageLibraryVo.FileItemVo> fileItemVoList = filePage.getRecords().stream()
                    .map(this::convertToFileItemVo)
                    .collect(Collectors.toList());
            
            fileListVo.setRecords(fileItemVoList);
            fileListVo.setCurrent((int) filePage.getCurrent());
            fileListVo.setPages((int) filePage.getPages());
            fileListVo.setTotal(filePage.getTotal());
            fileListVo.setSize(page.getSize());
            result.setFileList(fileListVo);

            return CommonResult.data(result);
        } catch (Exception e) {
            log.error("获取文件库列表失败", e);
            return CommonResult.error("获取文件库列表失败：" + e.getMessage());
        }
    }

    /**
     * 新增分组
     * 对应PHP的addGroup方法
     */
    @PostMapping("/addGroup")
    @Operation(summary = "新增分组")
    public CommonResult<ImageLibraryVo.GroupVo> addGroup(@RequestBody GroupParam param) {
        try {
            UploadGroup newGroup = uploadGroupService.addGroup(param.getGroupName(), "image");
            
            ImageLibraryVo.GroupVo groupVo = new ImageLibraryVo.GroupVo();
            groupVo.setGroupId(newGroup.getGroupId());
            groupVo.setGroupName(newGroup.getGroupName());
            groupVo.setSort(newGroup.getSort());
            
            return CommonResult.data(groupVo);
        } catch (Exception e) {
            log.error("新增分组失败", e);
            return CommonResult.error("新增分组失败：" + e.getMessage());
        }
    }

    /**
     * 编辑分组
     * 对应PHP的editGroup方法
     */
    @PostMapping("/editGroup")
    @Operation(summary = "编辑分组")
    public CommonResult<String> editGroup(@RequestBody GroupParam param) {
        try {
            boolean success = uploadGroupService.editGroup(param.getGroupId(), param.getGroupName());
            if (success) {
                return CommonResult.ok("修改成功");
            } else {
                return CommonResult.error("分组不存在或修改失败");
            }
        } catch (Exception e) {
            log.error("编辑分组失败", e);
            return CommonResult.error("编辑分组失败：" + e.getMessage());
        }
    }

    /**
     * 删除分组
     * 对应PHP的deleteGroup方法
     */
    @PostMapping("/deleteGroup/{groupId}")
    @Operation(summary = "删除分组")
    public CommonResult<String> deleteGroup(@PathVariable Long groupId) {
        try {
            boolean success = uploadGroupService.deleteGroup(groupId);
            if (success) {
                return CommonResult.ok("删除成功");
            } else {
                return CommonResult.error("分组不存在或删除失败");
            }
        } catch (Exception e) {
            log.error("删除分组失败", e);
            return CommonResult.error("删除分组失败：" + e.getMessage());
        }
    }

    /**
     * 移动文件到指定分组
     */
    @PostMapping("/moveFiles")
    @Operation(summary = "移动文件到指定分组")
    public CommonResult<String> moveFiles(@RequestBody GroupParam param) {
        try {
            for (Long fileId : param.getFileIds()) {
                UploadFile uploadFile = uploadService.getById(fileId);
                if (uploadFile != null) {
                    uploadFile.setGroupId(param.getGroupId());
                    uploadService.updateById(uploadFile);
                }
            }
            return CommonResult.ok("移动成功");
        } catch (Exception e) {
            log.error("移动文件失败", e);
            return CommonResult.error("移动文件失败：" + e.getMessage());
        }
    }

    /**
     * 批量删除文件
     */
    @PostMapping("/deleteFiles")
    @Operation(summary = "批量删除文件")
    public CommonResult<String> deleteFiles(@RequestBody List<Long> fileIds) {
        try {
            for (Long fileId : fileIds) {
                uploadService.deleteFile(fileId);
            }
            return CommonResult.ok("删除成功");
        } catch (Exception e) {
            log.error("批量删除文件失败", e);
            return CommonResult.error("批量删除文件失败：" + e.getMessage());
        }
    }

    /**
     * 转换为文件项VO
     */
    private ImageLibraryVo.FileItemVo convertToFileItemVo(UploadFile uploadFile) {
        ImageLibraryVo.FileItemVo fileItemVo = new ImageLibraryVo.FileItemVo();
        fileItemVo.setFileId(uploadFile.getFileId());
        fileItemVo.setFileName(uploadFile.getFileName());
        fileItemVo.setAlias(uploadFile.getAlias());
        fileItemVo.setFilePath(uploadFile.getFileUrl());
        fileItemVo.setFileUrl(uploadFile.getFileUrl());
        fileItemVo.setFileSize(uploadFile.getFileSize());
        fileItemVo.setFileType(uploadFile.getFileType());
        fileItemVo.setGroupId(uploadFile.getGroupId());
        fileItemVo.setCreateTime(uploadFile.getCreateTime());
        return fileItemVo;
    }
}
